import React, { useState, useEffect } from 'react'
import { Button, Card, Table, Space, Modal, Form, Input, Select, message } from "antd"
import { findAllUserApi,addUserApi } from "../../../apis/userApi"
import {findAllRoleApi} from "../../../apis/roleApi"
import useRequest from '../../../hooks/useRequest'
import {useSelector} from "react-redux"

const { Option } = Select;


const layout = {
  labelCol: {
    span: 4,
  },
  wrapperCol: {
    span: 16,
  },
};
const tailLayout = {
  wrapperCol: {
    offset: 4,
    span: 16,
  },
};

export default function User() {
  // const [dataSource, setDataSource] = useState([])
  const [roles,setRoles] = useState([])
  const [isModalOpen, setIsModalOpen] = useState(false);
  const {getUsers} = useRequest()
  const storeData = useSelector(state=>{
    return state.accountRD
  })

  useEffect(() => {
    // fetchData()
    getUsers()
    console.log(storeData);
  },[])

  // const fetchData = async () => {
  //   const res = await findAllUserApi()
  //   console.log(res);
  //   setDataSource(res.data.data)
  // }
  
  /**
   * 控制模态框的关闭
   */
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  /**
   * 表单区域需要用函数
   * @param {*} values 
   */
  const onFinish =async (values) => {
    console.log(values);
    const res = await addUserApi(values)
    console.log(res);
    if(res.data.code){
      message.success("添加成功")
      setIsModalOpen(false)
      // fetchData()
    }else{
      message.error("添加失败")
    }
  };
  const onFinishFailed = (error) => {
    console.log(error);
  }

  const addUser =async ()=>{
    setIsModalOpen(true)
    const res = await findAllRoleApi()
    setRoles(res.data.data)
  }
  
  // 表头的数据
  const columns = [
    {
      title: '用户名字',
      dataIndex: 'account',
    },
    {
      title: '邮箱地址',
      dataIndex: 'email',
    },
    {
      title: '用户角色',
      dataIndex: 'role',
      render:(params)=>{
        if(params){
          return params.name
        }else{
          return "不详"
        }
      }
    },
    {
      title: '操作',
      render: (p1, p2) => {
        return (
          <Space size="middle">
            <Button type='primary'>删除</Button>
          </Space>
        )
      }
    },
  ];


  return (
    <Card
      title={"用户列表"}
      extra={<Button onClick={addUser} type='primary'>添加</Button>}
      style={{
        width: "100%",
      }}
      loading={false}
    >
      <Table
        dataSource={storeData.users}
        columns={columns}
        rowKey="_id"
        bordered={true}
        loading={false}
        pagination={{ defaultCurrent: 1, defaultPageSize: 6, showSizeChanger: true, pageSizeOptions: [3, 6, 9], showQuickJumper: true }}

      />
      <Modal
        title="添加用户"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}>
        <Form
          {...layout}
          name="control-hooks"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          style={{
            maxWidth: 600,
          }}
        >
          <Form.Item
            name="account"
            label="用户名字"
            rules={[
              { required: true, message: "不允许为空" },
              // {min:5,message:"长度最少5个"}
              { pattern: /[0-9a-zA-Z\u4e00-\u9fa5_]{3,8}/, message: "允许字母数字中文,长度3-8" }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="password"
            label="用户密码"
          >
            <Input type="password" />
          </Form.Item>
          <Form.Item
            name="email"
            label="用户邮箱"
          >
            <Input/>
          </Form.Item>
          <Form.Item
            name="role"
            label="用户角色"
          >
            <Select
              placeholder="请选中一个角色"
              allowClear
            >
              {roles.map(item=>{
                return <Option key={item._id} value={item._id}>{item.name}</Option>
              })}
              
              
            </Select>
          </Form.Item>
          <Form.Item {...tailLayout}>
            <Space>
              <Button type="primary" htmlType="submit">
                Submit
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  )
}
